package ChaiPiao.util;

import java.util.Iterator;

/**
 * Created by w4ghe on 2017/3/9.
 */
public class CombineIterator implements Iterator {

    private int[] source;

    private int resultSize;

    private int size;

    private int[] index;

    private int offset = 0;

    public CombineIterator(int[] source, int resultSize) {
        if (source == null) throw new NullPointerException();
        int n = source.length;
        if (n < resultSize || resultSize <= 0)
            throw new IllegalArgumentException("size : " + n + ", m : " + resultSize);
        this.source = source;
        this.size = calcSize(n, resultSize);
        this.resultSize = resultSize;
        this.index = new int[resultSize];
        for (int i = 0; i < resultSize; i++) {
            this.index[i] = i;
        }
        this.index[resultSize - 1] -= 1;
    }

    private int calcSize(int n, int m) {
        return Factorial.factorial(n - m + 1, n).divide(Factorial.factorial(m)).intValue();
    }


    public int size() {
        return size;
    }

    public boolean hasNext() {
        return offset < size;
    }

    @Override
    public int[] next() {
        int idx = resultSize - 1;
        int n = source.length;
        if (index[idx] < n - 1) {
            index[idx] += 1;
        } else {
            idx -= 1;
            while (idx > 0 && index[idx] == index[idx + 1] - 1) {
                idx -= 1;
            }
            index[idx] += 1;
            for (int i = idx + 1; i <= resultSize - 1; i++) {
                index[i] = index[idx] + (i - idx);
            }
        }
        int[] result = new int[resultSize];
        for (int i = 0; i <= resultSize - 1; i++) {
            result[i] = source[index[i]];
        }
        offset++;
        return result;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

}